import { ref, onMounted, watch } from 'vue'

// NASA API 基础URL和密钥（这里使用Demo密钥，实际项目中应该从环境变量获取）
const API_BASE_URL = 'https://api.nasa.gov'
const API_KEY = 'DEMO_KEY' // 实际项目中应该使用环境变量: import.meta.env.VITE_NASA_API_KEY

// NASA API 组合式函数
export function useNASAAPI() {
  // 状态管理
  const loading = ref(false)
  const error = ref(null)
  const apiKey = ref(API_KEY)

  // APOD (每日天文图片) 相关
  const apodData = ref(null)
  const apodLoading = ref(false)
  const apodError = ref(null)

  // EPIC (地球多色成像相机) 相关
  const epicData = ref([])
  const epicDates = ref([])
  const epicLoading = ref(false)
  const epicError = ref(null)

  // Exoplanet Archive (系外行星) 相关
  const exoplanetData = ref([])
  const exoplanetLoading = ref(false)
  const exoplanetError = ref(null)

  // Mars Rover Photos (火星车照片) 相关
  const marsRoverPhotos = ref([])
  const roverCameras = ref([])
  const marsLoading = ref(false)
  const marsError = ref(null)

  // ISS Location (国际空间站位置) 相关
  const issLocation = ref(null)
  const issLoading = ref(false)
  const issError = ref(null)

  // Solar Activity (太阳活动) 相关
  const solarActivity = ref(null)
  const solarLoading = ref(false)
  const solarError = ref(null)

  // Moon Phase (月球相位) 相关
  const moonPhase = ref(null)
  const moonLoading = ref(false)
  const moonError = ref(null)

  // 通用请求函数
  const fetchData = async (endpoint, options = {}) => {
    loading.value = true
    error.value = null
    
    try {
      // 构建完整URL
      const url = new URL(`${API_BASE_URL}${endpoint}`)
      
      // 添加API密钥
      if (!endpoint.includes('api_key=')) {
        url.searchParams.append('api_key', apiKey.value)
      }
      
      // 添加其他查询参数
      if (options.params) {
        Object.entries(options.params).forEach(([key, value]) => {
          url.searchParams.append(key, value)
        })
      }

      // 发送请求
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        },
        ...options
      })

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`)
      }

      const data = await response.json()
      loading.value = false
      return data
    } catch (err) {
      console.error('API请求错误:', err)
      error.value = err.message || '请求失败'
      loading.value = false
      throw err
    }
  }

  // APOD (每日天文图片) 相关函数
  const getAPOD = async (date = null, count = 1) => {
    apodLoading.value = true
    apodError.value = null

    try {
      const params = {}
      
      if (date) {
        params.date = date
      }
      
      if (count > 1) {
        params.count = count
      }

      const data = await fetchData('/planetary/apod', { params })
      
      // 如果是单张图片，直接赋值
      if (count === 1) {
        apodData.value = data
      } else {
        // 多张图片返回数组
        apodData.value = data
      }
      
      apodLoading.value = false
      return apodData.value
    } catch (err) {
      apodError.value = err.message || '获取每日天文图片失败'
      apodLoading.value = false
      throw err
    }
  }

  // EPIC (地球多色成像相机) 相关函数
  const getEPICDates = async () => {
    epicLoading.value = true
    epicError.value = null

    try {
      const data = await fetchData('/EPIC/api/natural/available')
      epicDates.value = data
      epicLoading.value = false
      return data
    } catch (err) {
      epicError.value = err.message || '获取EPIC可用日期失败'
      epicLoading.value = false
      throw err
    }
  }

  const getEPICImages = async (date = null) => {
    epicLoading.value = true
    epicError.value = null

    try {
      // 如果没有提供日期，使用最近的日期
      if (!date && epicDates.value.length > 0) {
        date = epicDates.value[epicDates.value.length - 1]
      }
      
      // 格式化日期为YYYY-MM-DD
      const formattedDate = date.replace(/\//g, '-')
      
      // 获取当天的EPIC图片数据
      const data = await fetchData(`/EPIC/api/natural/date/${formattedDate}`)
      
      // 添加完整的图片URL
      const imagesWithUrl = data.map(img => ({
        ...img,
        imageUrl: `${API_BASE_URL}/EPIC/archive/natural/${formattedDate.replace(/-/g, '/')}/png/${img.image}.png?api_key=${apiKey.value}`,
        thumbnailUrl: `${API_BASE_URL}/EPIC/archive/natural/${formattedDate.replace(/-/g, '/')}/thumb/${img.image}.png?api_key=${apiKey.value}`
      }))
      
      epicData.value = imagesWithUrl
      epicLoading.value = false
      return imagesWithUrl
    } catch (err) {
      epicError.value = err.message || '获取EPIC图片失败'
      epicLoading.value = false
      throw err
    }
  }

  // Exoplanet Archive (系外行星) 相关函数
  const getExoplanets = async (limit = 20, sortBy = 'discovery_date') => {
    exoplanetLoading.value = true
    exoplanetError.value = null

    try {
      // Exoplanet Archive API 使用不同的URL结构
      const url = `https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets&select=pl_name,hostname,discoverymethod,discovery_date,pl_orbper,pl_orbsmax,pl_bmasse,st_mass,st_rad&format=json&order=desc&limit=${limit}&ordercolumn=${sortBy}`
      
      const response = await fetch(url)
      
      if (!response.ok) {
        throw new Error(`Exoplanet Archive请求失败: ${response.status}`)
      }
      
      const data = await response.json()
      exoplanetData.value = data
      exoplanetLoading.value = false
      return data
    } catch (err) {
      exoplanetError.value = err.message || '获取系外行星数据失败'
      exoplanetLoading.value = false
      throw err
    }
  }

  // Mars Rover Photos (火星车照片) 相关函数
  const getMarsRoverPhotos = async (rover = 'curiosity', sol = 1000, camera = null, page = 1) => {
    marsLoading.value = true
    marsError.value = null

    try {
      const params = { sol, page }
      
      if (camera) {
        params.camera = camera
      }

      const data = await fetchData(`/mars-photos/api/v1/rovers/${rover}/photos`, { params })
      
      // 如果需要存储相机列表
      if (!roverCameras.value.length && data.photos.length > 0) {
        roverCameras.value = [...new Set(data.photos.map(photo => photo.camera.full_name))]
      }
      
      marsRoverPhotos.value = data.photos
      marsLoading.value = false
      return data.photos
    } catch (err) {
      marsError.value = err.message || '获取火星车照片失败'
      marsLoading.value = false
      throw err
    }
  }

  // 获取可用的火星车列表
  const getMarsRovers = async () => {
    try {
      const data = await fetchData('/mars-photos/api/v1/rovers')
      return data.rovers
    } catch (err) {
      console.error('获取火星车列表失败:', err)
      return []
    }
  }

  // ISS Location (国际空间站位置) 相关函数
  const getISSLocation = async () => {
    issLoading.value = true
    issError.value = null

    try {
      // 使用Open Notify API获取ISS位置
      const response = await fetch('http://api.open-notify.org/iss-now.json')
      
      if (!response.ok) {
        throw new Error(`ISS位置请求失败: ${response.status}`)
      }
      
      const data = await response.json()
      issLocation.value = {
        timestamp: data.timestamp,
        latitude: parseFloat(data.iss_position.latitude),
        longitude: parseFloat(data.iss_position.longitude),
        // 添加时间格式化
        timeString: new Date(data.timestamp * 1000).toLocaleString()
      }
      
      issLoading.value = false
      return issLocation.value
    } catch (err) {
      issError.value = err.message || '获取国际空间站位置失败'
      issLoading.value = false
      throw err
    }
  }

  // Solar Activity (太阳活动) 相关函数
  const getSolarActivity = async (startDate = null, endDate = null) => {
    solarLoading.value = true
    solarError.value = null

    try {
      // 如果没有提供日期，使用默认范围
      const today = new Date()
      const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
      
      const params = {
        start_date: startDate || sevenDaysAgo.toISOString().split('T')[0],
        end_date: endDate || today.toISOString().split('T')[0]
      }

      // 获取太阳黑子数据
      const sunspotsData = await fetchData('/DONKI/ssn', { params })
      
      // 获取太阳耀斑数据
      const flaresData = await fetchData('/DONKI/FLR', { params })
      
      solarActivity.value = {
        sunspots: sunspotsData,
        flares: flaresData
      }
      
      solarLoading.value = false
      return solarActivity.value
    } catch (err) {
      solarError.value = err.message || '获取太阳活动数据失败'
      solarLoading.value = false
      throw err
    }
  }

  // Moon Phase (月球相位) 相关函数
  const getMoonPhase = async (date = null) => {
    moonLoading.value = true
    moonError.value = null

    try {
      const params = {}
      
      if (date) {
        params.date = date
      }

      // 使用NASA的Moon Phase API（如果可用）或第三方API
      // 这里使用模拟数据，实际项目中应替换为真实API
      
      // 模拟的月球相位数据
      const today = date ? new Date(date) : new Date()
      const daysInYear = (today.getFullYear() % 4 === 0 && today.getFullYear() % 100 !== 0) || today.getFullYear() % 400 === 0 ? 366 : 365
      const dayOfYear = Math.floor((today - new Date(today.getFullYear(), 0, 0)) / 86400000)
      const lunarAge = (dayOfYear * 29.530588853) % 29.530588853
      
      let phase = ''
      let phaseEmoji = ''
      
      if (lunarAge < 1) {
        phase = '新月'
        phaseEmoji = '🌑'
      } else if (lunarAge < 6.38) {
        phase = '眉月'
        phaseEmoji = '🌒'
      } else if (lunarAge < 12.76) {
        phase = '上弦月'
        phaseEmoji = '🌓'
      } else if (lunarAge < 19.15) {
        phase = '盈凸月'
        phaseEmoji = '🌔'
      } else if (lunarAge < 24.53) {
        phase = '满月'
        phaseEmoji = '🌕'
      } else if (lunarAge < 27.24) {
        phase = '亏凸月'
        phaseEmoji = '🌖'
      } else if (lunarAge < 29.53) {
        phase = '下弦月'
        phaseEmoji = '🌗'
      } else {
        phase = '残月'
        phaseEmoji = '🌘'
      }
      
      const mockData = {
        date: today.toISOString().split('T')[0],
        phase,
        phaseEmoji,
        lunarAge: lunarAge.toFixed(2),
        illumination: ((Math.sin(lunarAge * Math.PI / 29.530588853) + 1) / 2 * 100).toFixed(2),
        nextFullMoon: new Date(today.getTime() + (29.530588853 - lunarAge) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        nextNewMoon: new Date(today.getTime() + (29.530588853/2 - lunarAge) * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
      }
      
      moonPhase.value = mockData
      moonLoading.value = false
      return mockData
    } catch (err) {
      moonError.value = err.message || '获取月球相位数据失败'
      moonLoading.value = false
      throw err
    }
  }

  // 设置API密钥
  const setAPIKey = (key) => {
    apiKey.value = key
    // 可以将API密钥保存到localStorage
    localStorage.setItem('nasaApiKey', key)
  }

  // 从localStorage加载API密钥
  const loadAPIKey = () => {
    const savedKey = localStorage.getItem('nasaApiKey')
    if (savedKey) {
      apiKey.value = savedKey
    }
  }

  // 初始化函数
  const init = async () => {
    loadAPIKey()
    
    // 预加载一些基础数据
    try {
      // 预加载EPIC日期列表
      await getEPICDates()
      
      // 获取当前月球相位
      await getMoonPhase()
      
      // 获取国际空间站位置
      await getISSLocation()
      
    } catch (err) {
      console.error('初始化数据失败:', err)
    }
  }

  // 暴露的函数和状态
  return {
    // 通用状态
    loading,
    error,
    apiKey,
    setAPIKey,
    loadAPIKey,
    init,
    
    // APOD
    apodData,
    apodLoading,
    apodError,
    getAPOD,
    
    // EPIC
    epicData,
    epicDates,
    epicLoading,
    epicError,
    getEPICDates,
    getEPICImages,
    
    // Exoplanets
    exoplanetData,
    exoplanetLoading,
    exoplanetError,
    getExoplanets,
    
    // Mars Rover
    marsRoverPhotos,
    roverCameras,
    marsLoading,
    marsError,
    getMarsRoverPhotos,
    getMarsRovers,
    
    // ISS Location
    issLocation,
    issLoading,
    issError,
    getISSLocation,
    
    // Solar Activity
    solarActivity,
    solarLoading,
    solarError,
    getSolarActivity,
    
    // Moon Phase
    moonPhase,
    moonLoading,
    moonError,
    getMoonPhase
  }
}